//
//  FBDDownload.m
//  AVPlayerTest
//
//  Created by feng on 16/9/20.
//  Copyright © 2016年 冯宝东. All rights reserved.
//

#import "FBDDownload.h"
#import "AppDelegate.h"
@interface FBDDownload ()<NSURLSessionDelegate>
@property (nonatomic, strong) NSURLSessionDownloadTask *task;
@property (nonatomic, strong) NSData *resumeData;
@property (nonatomic, strong) NSURLSession *session;
@property (nonatomic,strong)NSString *myURL;

@end
@implementation FBDDownload

-(instancetype)initWithDownLoadURL:(NSString*)url
{
    self=[super init];
    if (self) {
        _myURL=url;
        NSURLSessionConfiguration *cfg=[NSURLSessionConfiguration defaultSessionConfiguration];
        self.session=[NSURLSession sessionWithConfiguration:cfg delegate:self delegateQueue:[NSOperationQueue mainQueue]];
        
        self.task=[self.session downloadTaskWithURL:[NSURL URLWithString:url]];
        [self.task resume];
    }
    return self;

}

//关闭正在下载的链接
-(void)cancelIndexDownLoad
{
    [self.session invalidateAndCancel];

}

#pragma mark - NSURLSessionDownloadDelegate
- (void)URLSession:(NSURLSession *)session downloadTask:(NSURLSessionDownloadTask *)downloadTask
didFinishDownloadingToURL:(NSURL *)location
{
    NSString *caches = [NSSearchPathForDirectoriesInDomains(NSCachesDirectory, NSUserDomainMask, YES) lastObject];
    // response.suggestedFilename ： 建议使用的文件名，一般跟服务器端的文件名一致
    NSString *file = [caches stringByAppendingPathComponent:downloadTask.response.suggestedFilename];
    NSLog(@"下载结束的回调路径： %@ size:%ld",file ,location.dataRepresentation.length);
    
    // 将临时文件剪切或者复制Caches文件夹
    NSFileManager *mgr = [NSFileManager defaultManager];
    
    
    
    // AtPath : 剪切前的文件路径
    // ToPath : 剪切后的文件路径
    [mgr moveItemAtPath:location.path toPath:file error:nil];
    if (self.completeDownBlock) {
        self.completeDownBlock(downloadTask.currentRequest.URL.absoluteString,YES,file);
    }
}


- (void)URLSession:(NSURLSession *)session downloadTask:(NSURLSessionDownloadTask *)downloadTask
      didWriteData:(int64_t)bytesWritten
 totalBytesWritten:(int64_t)totalBytesWritten
totalBytesExpectedToWrite:(int64_t)totalBytesExpectedToWrite
{
    //NSLog(@"获得下载进度--%@", [NSThread currentThread]);
    // 获得下载进度
    float progress = (double)totalBytesWritten / totalBytesExpectedToWrite;
    if (_currentDownBlock)
    {
        _currentDownBlock(_myURL,progress);
    }
   // NSLog(@"download progress is %.2f",progress);
}

- (void)URLSession:(NSURLSession *)session downloadTask:(NSURLSessionDownloadTask *)downloadTask
 didResumeAtOffset:(int64_t)fileOffset
expectedTotalBytes:(int64_t)expectedTotalBytes
{
    
    
}


- (void)URLSession:(NSURLSession *)session task:(NSURLSessionTask *)task
didCompleteWithError:(nullable NSError *)error
{
    if (error) {
        if (self.completeDownBlock) {
            self.completeDownBlock(task.currentRequest.URL.absoluteString,NO,nil);
        }
        
    }else
    {
    
    }


}

- (void)URLSessionDidFinishEventsForBackgroundURLSession:(NSURLSession *)session

{
    
    AppDelegate *appDelegate = (AppDelegate *)[[UIApplication sharedApplication] delegate];
    
    if (appDelegate.backgroundSessionCompletionHandle) {
    
        void (^completionHandler)() = appDelegate.backgroundSessionCompletionHandle;
        
        appDelegate.backgroundSessionCompletionHandle = nil;
        
        completionHandler();
        
    }
    
    
    
    NSLog(@"All tasks are finished");
    
}

 /*******************************************自定义回调********************************************************************/
//设置当前的进度回调
-(void)fbdDownloadConfigeCurrentDownloadBlock:(downloadCurrentBlock)downBlock
{
    self.currentDownBlock=downBlock;
    
}
//设置当前下载完成的回调
-(void)fbdDownloadConfigeCompleteDownloadBlock:(downloadCompleteBlock)downBlock
{
    self.completeDownBlock=downBlock;
    
}


@end
